
#ifndef __SERVER_H__
#define __SERVER_H__

#include "common.h"
#include "connection.h"
#include "ae.h"
#include "iothreadpool.h"
#include "logger.h"

class Server
{
public:
    Server()
    {
        sockfd_ = 0;
        port_ = 0;
        stop_ = 0;
        io_thread_active_ = false;
        io_thread_num_ = 4;
        el_ = nullptr;
    }

    ~Server()
    {
        //delete el_;
        tcfree(eventLoop, el_);
        el_ = nullptr;
    }

    void initServer(int port = 8080);

    void clientInstallWriteHandler(connection* conn);


    void freeClientAsync(connection *c);
    void freeClient(connection* conn);
    int freeClientsInAsyncFreeQueue();

    int handleClientsWithPendingReadsUsingThreads();
    int handleClientsWithPendingWrites();
    bool stopThreadIOIfNeeded();
    int handleClientsWithPendingWritesUsingThreads();
public:
    int sockfd_;
    int port_;
    int stop_;
    eventLoop* el_;
    IOThreadPool* io_thread_;

    bool io_thread_active_;
    int io_thread_num_;

    //TODO怎么加到全局队列中，再负载均衡到io队列中
    std::list<connection*> clients_to_close_;//异步关闭connection
    std::list<connection*> clients_pending_write_;
    std::list<connection*> clients_pending_read_;

};

extern Server server;

#endif
